import { useEffect, useMemo, useState } from 'react'
import { useMemoizedFn } from 'ahooks'
import { Button, message, Modal, Tooltip } from 'antd'
import Icon from '@ant-design/icons'
import { RowSelectionOptions, SelectionChangedEvent } from '@ag-grid-community/core'

import { CusAgGrid, ICusAgGridProps } from '@/components/CusAgGrid'
import { UnifiedPagination } from '@/components/UnifiedPagination'
import { addAGCellTexty } from '@oBiz/components/addTexty'
import { EmailbodyPreviewModal } from '../EmailbodyPreviewModal'
import { ITemplate, TTemplateCol, TTemplateParams } from '../interface'
import { popupSlot } from '../utils'
import { useBoundStore } from './store'
import { useTemplateList } from './useTemplateList'
import PrviewMailIcon from '@/assets/icons/prviewMail.svg?react'
import styles from './styles.module.less'
const updatePopup = popupSlot.insert(null)

interface IMailTemplateListModalProps {
  /** 成功时的回调 */
  onSuccess?: (list: ITemplate[]) => void
}

const ActionCell = ({ data }: TTemplateParams) => {
  if (!data) return
  return (
    <Tooltip title="邮件正文模版预览">
      <Button
        type="link"
        icon={
          <Icon
            component={PrviewMailIcon}
            onClick={() => {
              const update = popupSlot.insert(
                <EmailbodyPreviewModal
                  title={data.title ?? data.templateId}
                  templateId={data.templateId}
                  htmlBody={data.htmlBody}
                  destroy={() => update(null)}
                />,
              )
            }}
          />
        }
      />
    </Tooltip>
  )
}

const Cell = (p: TTemplateParams) => {
  const { field } = p.colDef || {}
  switch (field) {
    case 'htmlBody': {
      return <ActionCell {...p} />
    }
    default: {
      return addAGCellTexty(p)
    }
  }
}

export const MailTemplateListModal = Object.assign(
  ({ onSuccess, destroy }: IMailTemplateListModalProps & { destroy: () => void }) => {
    useTemplateList()
    const [activeTemplate, setActiveTemplate] = useState<ITemplate[]>([])
    const { open, onHide, afterOpenChange } = popupSlot.useAntdPopupAnimation(destroy)
    const gridRef = useBoundStore(v => v.gridRef)
    const loading = useBoundStore(v => v.request?.loading)
    const data = useBoundStore(v => v.request?.data)
    const page = useBoundStore(v => v.reqData.page)
    const size = useBoundStore(v => v.reqData.size)
    const setReqData = useBoundStore(v => v.setReqData)
    const getData = useBoundStore(v => v.getData)

    // 列配置
    const defaultColDef = useMemo<Partial<TTemplateCol>>(
      () => ({
        flex: 1,
        minWidth: 180,
        sortable: false,
        cellRenderer: Cell,
      }),
      [],
    )
    const columnDefs = useMemo(
      () =>
        [
          {
            field: 'templateId',
            headerName: '模板ID',
          },
          {
            field: 'title',
            headerName: '模板标题',
            flex: 2.5,
          },
          {
            field: 'type',
            headerName: '模板类型',
          },
          {
            field: 'htmlBody',
            headerName: '操作',
            flex: 0.01,
            width: 100,
            minWidth: 100,
            pinned: 'right',
          },
        ] satisfies TTemplateCol[],
      [],
    )

    // 分页器
    const statusBar = useMemo<ICusAgGridProps['statusBar']>(() => {
      return {
        statusPanels: [
          {
            statusPanel: UnifiedPagination,
            statusPanelParams: UnifiedPagination.defineProps({
              current: page,
              pageSize: size,
              total: data?.total,
              onChange: (page, size) => {
                setReqData({ page, size })
                getData({ page, size })
              },
            }),
          },
        ],
      }
    }, [data?.total, getData, page, setReqData, size])

    // 行勾选
    const rowSelection = useMemo<RowSelectionOptions | 'single' | 'multiple'>(() => {
      return { mode: 'singleRow', headerCheckbox: false }
    }, [])

    // 列表勾选
    const onSelectionChanged = (event: SelectionChangedEvent<ITemplate>) => {
      const selectRows = event.api.getSelectedRows()
      setActiveTemplate(selectRows)
    }

    const submitHandler = useMemoizedFn(() => {
      if (!activeTemplate.length) return message.warning('请选择一个邮件模板')
      onSuccess?.(activeTemplate)
      onHide()
    })

    // 清理，保留筛选条件
    useEffect(
      () => () =>
        useBoundStore.setState({ ...useBoundStore.getInitialState(), reqData: useBoundStore.getState().reqData }, true),
      [],
    )

    return (
      <Modal
        title="邮件模板绑定"
        width={1300}
        onCancel={onHide}
        open={open}
        afterOpenChange={afterOpenChange}
        onOk={submitHandler}
      >
        <div className={styles.box}>
          {/* <div className={styles.header}>
            <Input.Search
              style={{ width: 300 }}
              placeholder="请输入模板标题"
              allowClear
              onSearch={value => {
                setReqData({ title: value })
                getData({ title: value })
              }}
            />
          </div> */}
          <div className={styles.main}>
            <CusAgGrid<ITemplate>
              ref={gridRef}
              loading={loading}
              rowData={data?.records}
              defaultColDef={defaultColDef}
              columnDefs={columnDefs}
              statusBar={statusBar}
              rowSelection={rowSelection}
              onSelectionChanged={onSelectionChanged}
            />
          </div>
        </div>
      </Modal>
    )
  },
  {
    open: (props: IMailTemplateListModalProps) => {
      updatePopup(<MailTemplateListModal {...props} destroy={() => updatePopup(null)} />)
    },
  },
)
